#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define ATM_NUM 9
#define PEOPLE_NUM 10
#define MIN_ATM_TIME 3
#define MAX_ATM_TIME 6

#define LOCK pthread_mutex_lock( &g_ptmxAtmMute )
#define UNLOCK pthread_mutex_unlock( &g_ptmxAtmMute )

int g_AtmNum = ATM_NUM;
pthread_mutex_t g_ptmxAtmMute;

int GetRandAtmTime()
{
    int iRet;
    srand( time(NULL) );
    iRet = rand() % (MAX_ATM_TIME - MIN_ATM_TIME + 1) +  MIN_ATM_TIME;
    return iRet;

}

void * GetATM( void * arg )
{
    while (1)
    {
        LOCK;
        if ( g_AtmNum >0 )
        {
            g_AtmNum--;
            printf( "Thread %ld Get ATM\n", pthread_self() );
            UNLOCK;

            sleep( GetRandAtmTime() );

            LOCK;
            g_AtmNum++;
            printf( "Thread %ld Rls ATM\n", pthread_self() );
            UNLOCK;
            pthread_exit( NULL );
        }
        else
        {
            UNLOCK;
        }
        

    }
}


int main(int argc, char const *argv[])
{
    time_t timeStart = time(NULL);

    pthread_mutex_init( &g_ptmxAtmMute, NULL );
    
    pthread_t ptFun[PEOPLE_NUM] = {0};
    
    int i;
    for( i=0; i<PEOPLE_NUM; i++ )
    {
        pthread_create( &ptFun[i] , NULL , GetATM, NULL );
    }

    for( i=0; i<PEOPLE_NUM; i++ )
    {
        pthread_join( ptFun[i], NULL );
    }

    pthread_mutex_destroy( &g_ptmxAtmMute );

    
    time_t timeEnd = time( NULL );

    printf("Total Time %ld\n", timeEnd - timeStart );

    return 0;
}






/*
		2.ATM取钱问题:
		
		int atm = 3
		   
		有3个ATM机,10个人取钱,用线程模拟取钱的过程
		
		获得ATM机atm-1
		sleep(rand()%10) 模拟取钱消耗时间
		释放ATM机atm+1
		
		创建10个线程,模拟进入ATM机取钱的过程

*/